package com.sskj.givecoin.v.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.just.agentweb.AgentWeb;
import com.sskj.givecoin.R;
import com.sskj.givecoin.common.App;
import com.sskj.givecoin.common.Constants;
import com.sskj.givecoin.common.widget.ToolBarLayout;
import com.sskj.givecoin.m.HttpConfig;
import com.sskj.givecoin.m.bean.Notice;
import com.sskj.givecoin.p.activity.NoticeDetailPresenter;
import com.sskj.givecoin.utils.TimeFormatUtil;
import com.sskj.givecoin.v.base.BaseActivity;
import com.zzhoujay.richtext.RichText;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;

public class WebViewActivity extends BaseActivity<NoticeDetailPresenter> {
    @BindView(R.id.web_toolbar)
    ToolBarLayout webToolbar;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.ll_web)
    LinearLayout llWeb;
    @BindView(R.id.content)
    TextView contentText;

    private AgentWeb mAgentWeb;
    private String noticeId;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_web_view;
    }

    @Override
    public NoticeDetailPresenter getPresenter() {
        return new NoticeDetailPresenter();
    }

    @Override
    protected void initView() {
        noticeId = getIntent().getStringExtra(Constants.INTENT_NOTICE_ID);
        webToolbar.setLeftButtonOnClickLinster(v -> finish());
        initWeb();
        if (noticeId.equals("reg_agree")) {
            webToolbar.setTitle(App.INSTANCE.getString(R.string.strWebViewActivity201));
            mPresenter.getAgree(noticeId);
        } else if (noticeId.equals("facebook")) {
            contentText.setVisibility(View.GONE);
            webToolbar.setTitle("FaceBook");
            mAgentWeb.getWebCreator().getWebView().loadUrl("https://www.facebook.com/GoCoiner");
        } else if (noticeId.equals("github")) {
            contentText.setVisibility(View.GONE);
            webToolbar.setTitle("GitHub");
            mAgentWeb.getWebCreator().getWebView().loadUrl("https://github.com/GoCoin");
        } else if (noticeId.equals("twitter")) {
            contentText.setVisibility(View.GONE);
            webToolbar.setTitle("Twitter");
            mAgentWeb.getWebCreator().getWebView().loadUrl("https://gocoin.com/twitter");
        } else if (noticeId.equals("trans_agree")) {
            webToolbar.setTitle(App.INSTANCE.getString(R.string.fabimineJavaWebViewActivity12));
            mPresenter.getAgree(noticeId);
            contentText.setVisibility(View.VISIBLE);
        } else {
            webToolbar.setTitle(App.INSTANCE.getString(R.string.strWebViewActivity202));
            mPresenter.getData(noticeId);
        }
    }

    private void initWeb() {
        ((ViewGroup) (webView.getParent())).removeView(webView);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");//设置默认为utf-8
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        //此方法不支持4.4以后
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setJavaScriptEnabled(true);

//        webView.setLayerType(View.LAYER_TYPE_NONE, null);
        mAgentWeb = AgentWeb.with(this)//这里需要把 Activity 、 和 Fragment  同时传入
                .setAgentWebParent(llWeb, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator(Color.TRANSPARENT)// 使用默认进度条
                .setWebView(webView)
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //注意这里开启 strict 模式 ， 设备低于 4.2 情况下回把注入的 Js 全部清空掉 ， 这里推荐使用 onJsPrompt 通信
                .createAgentWeb()
                .ready()
                .go("");
    }


    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            Log.i("Info", "BaseWebActivity onPageStarted");
        }

        @Override
        public void onPageFinished(WebView webView, String url) {
            imgReset();
//            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) webView.getLayoutParams();
//            params.width = ScreenUtils.getScreenWidth(WebViewActivity.this);
//            params.height = ScreenUtils.getScreenHeight(WebViewActivity.this) - webView.getTop();
//            webView.setLayoutParams(params);
        }
    };

    //此方法获取里面的img，设置img的高度100%,固定图片不能左右滑动
    private void imgReset() {
        webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var img = objs[i];   " +
                " img.style.maxWidth = '100%';img.style.height='auto';" +
                "}" +
                "})()");
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);

        }
    };

    /**
     * 开启web页面
     *
     * @param context
     */
    public static void start(Context context, String noticeId) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(Constants.INTENT_NOTICE_ID, noticeId);
        context.startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
    }

    public void loadData(Notice datas) {
        Log.i("info", datas.toString());
//        setTitle(datas.getTitle());
        String content = datas.getContent().replaceAll("<span.*?</span><span.*?</span>", "");
        content = "<h3 style=\" color:#333333\">" + datas.getTitle() + "</h3>\n" +
                "<font size=\"3\" color=\"#9EA8AD\">" + TimeFormatUtil.SF_FORMAT_E.format(datas.getCreate_time() * 1000) + "</font><br/>" + content;
//        mAgentWeb.getUrlLoader().loadData(content, "text/html; charset=UTF-8", null);


        RichText.from(formatImg(content)).into(contentText);
    }

    public void loadData(String data) {
//        mAgentWeb.getUrlLoader().loadData(data, "text/html; charset=UTF-8", null);
        RichText.from(formatImg(data)).into(contentText);
    }

    public String formatImg(String content) {
        Document document = Jsoup.parse(content);
        Elements imgs = document.getElementsByTag("img");
        for (int i = 0; i < imgs.size(); i++) {
            Element img = imgs.get(i);
            img.attr("width", "100%").attr("height", "auto");
            String url = img.attr("src");
            if (!url.contains("http")) {
                url = HttpConfig.BASE_URL + url;
            }
            img.attr("src", url);
        }
        return document.toString();
    }

}
